import { defineStore } from "pinia";

interface IUserState {
  menus?: IMenus[];
  username?:string;
}

interface TMenusType {
  id: number;
  parentId: number;
  title:string;
  name:string;
  icon:string|null;
  children?: IMenus[];
}

export const useUserState = defineStore("user", {
  state: (): IUserState => ({
    menus: [],
    username:''
  }),
  getters: {
    getMenusRoutes(state) {
      // 定义一个变量储存
      // const
      const newMenus:{[k:number]:TMenusType} = {};
      if(!state.menus)return;
      state.menus.forEach((item) => {
        if (item.parentId == 0) {
          //一级目录
          // newMenus.push(item); //数组是索引的
          
          newMenus[item.id] = {
            ...item,
            // children:[]
            children:newMenus[item.id]?.children
          }; //newMenus[97]//newMenus[118]
        } else {
          //二级菜单
          newMenus[item.parentId] ??= {} as TMenusType;
          newMenus[item.parentId].children ??=[]; //null赋值运算符
          newMenus[item.parentId].children!.push(item);
        }
      });
      
      return newMenus
    },
    getPermitions(state){
      return state.menus?.map(item=>item.name)
    }
  },
  actions: {
    updatedMenus(data: IUserState): void {
      this.menus = data.menus;
      this.username=data.username;
    },
  },
});
